import asyncio
from threading import Thread

from PySide6.QtCore import *
from PySide6.QtGui import QPixmap, QAction
from PySide6.QtNetwork import *
from PySide6.QtWebEngineCore import *
from PySide6.QtWebEngineWidgets import *
from PySide6.QtWidgets import *

from config import USERS
from .ui_main import Ui_MainWindow
from .unit import S
from .web import *
import mitmproxy.http
import mitmproxy
from mitmproxy import ctx
from mitmproxy.options import Options
from mitmproxy.tools.dump import DumpMaster


class Main(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.setFixedSize(self.size())
        self.pxx = QStackedWidget(self)
        self.pxx.setFixedWidth(500)
        self.webEngineView.deleteLater()
        self.horizontalLayout_3.insertWidget(0, self.pxx)
        self.load_user()
        self.server = Thread(target=self.on_sever, daemon=True)
        self.server.start()

        self.tableWidget.setSelectionBehavior(QTableWidget.SelectRows)
        self.tableWidget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tableWidget.itemSelectionChanged.connect(self._show_pic)
        self.tableWidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tableWidget.customContextMenuRequested.connect(self._creat_menu)
        self.tableWidget.setSortingEnabled(True)

        self.pic_manager = QNetworkAccessManager(self)
        self.pic_manager.finished.connect(self._set_label_pic)

        self.pushButton_2.clicked.connect(self.on_listen)
        self.pushButton_3.clicked.connect(self.off_listen)
        self.pushButton_4.clicked.connect(self.load_home)
        S.item.connect(self.add_item)
        self.comboBox.currentIndexChanged.connect(self.user_changed)

    def user_changed(self, index):
        self.pxx.setCurrentIndex(index)
        print(self.web().page().profile().isOffTheRecord())
        print(self.web()._profile.isOffTheRecord())
        print('---------------------------')

    @Slot()
    def add_item(self, item:list):

        def _add(col, value):
            item = QTableWidgetItem()
            item.setData(Qt.DisplayRole, value)
            self.tableWidget.setItem(0, col, item)

        self.tableWidget.insertRow(0)
        [_add(m, value) for m, value in enumerate(item)]

    def on_listen(self):
        S.监听 = True
        S.auto = True
        self.web().on_listen()

    def off_listen(self):
        S.监听 = False
        S.auto = False
        self.resize_table()

    def load_user(self):
        for user in USERS:
            web = PDDWeb(user)
            self.pxx.addWidget(web)
            self.comboBox.addItem(user, userData=web)

    def web(self) -> PDDWeb:
        return self.pxx.currentWidget()

    def load_home(self):
        self.web().load(QUrl('https://mobile.pinduoduo.com'))

    def on_sever(self):
        mitmproxy_options = Options()
        mitmproxy_options.add_option("ssl_insecure", bool, True, "Ignore SSL certificate verification")
        mitmproxy_options.listen_host = "127.0.0.1"  # 监听主机
        mitmproxy_options.listen_port = 3969  # 监听端口
        loop = asyncio.new_event_loop()
        master = DumpMaster(options=mitmproxy_options, with_termlog=False, with_dumper=False, loop=loop)

        # 添加自定义 addons 规则
        master.addons.add(TryAddon())
        # 使用协程运行mitmproxy
        asyncio.run(master.run())

    def _show_pic(self):
        """
        发起图像请求
        :return:
        """
        row = self.tableWidget.currentRow()
        item = self.tableWidget.item(row, 6)
        if item:
            url = item.text()
            request = QNetworkRequest(QUrl(url))
            self.pic_manager.get(request)

    def _set_label_pic(self, reply: QNetworkReply):
        """
        将收到的二进制图像呫在label上
        :param reply: 网络回应
        :return:
        """
        img_data = reply.readAll()
        pixmap = QPixmap()
        pixmap.loadFromData(img_data)
        # 将图像缩放与label一致大小
        pixmap = pixmap.scaled(self.label.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)
        # 在标签中设置图像
        self.label.setPixmap(pixmap)

    def resize_table(self):
        """
        调整表格显示
        :return:
        """

        def table_length():
            """
            计算表格尺寸
            :return:
            """
            table = self.tableWidget
            w1 = table.verticalHeader().width() if table.verticalHeader().isVisible() else 0
            w2 = table.verticalScrollBar().width() if table.verticalScrollBar().isVisible() else 0
            return table.width() - w1 - w2

        jd1_b = [0, 8, 1, 1, 1, 1.3, 0]
        c = [table_length() * (j / sum(jd1_b)) for j in jd1_b]
        [self.tableWidget.setColumnWidth(i, c[i]) for i in range(self.tableWidget.columnCount())]

    def _creat_menu(self, pos):

        def open_url():
            self.web().load(QUrl(url))

        menu = QMenu(self)
        ac1 = QAction('查看详情', self, triggered=open_url)
        menu.addAction(ac1)
        item = self.tableWidget.itemAt(pos)
        if item:
            S.item = item
            productId = self.tableWidget.item(item.row(), 0).text()
            url = f'https://mobile.pinduoduo.com/hub_free_trial_goods.html?trial_id={productId}'
            menu.exec_(self.tableWidget.mapToGlobal(pos))